from flask import request,jsonify
from .. import db
import os
import requests
from app.users.model import Users
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
from .WXBizDataCrypt import WXBizDataCrypt

class User(object):
    def add_to_16(text):
        if len(text.encode('utf-8')) % 16 :
            add =16-(len(text.encode('utf-8')) % 16)
        else:
            add = 0
        text = text + ('\0' * add)
        return text.encode('utf-8')

    # 加密函数
    def encrypt(text):
        key = '9999999999999999'.encode('utf-8')
        mode = AES.MODE_ECB
        text = User.add_to_16(text)
        cryptos = AES.new(key, mode)
        cipher_text = cryptos.encrypt(text)
        return b2a_hex(cipher_text)


    # 解密后，去掉补足的空格用strip() 去掉
    def decrypt(text):
        key = '9999999999999999'.encode('utf-8')
        mode = AES.MODE_ECB
        cryptor = AES.new(key, mode)
        plain_text = cryptor.decrypt(a2b_hex(text))
        return bytes.decode(plain_text).rstrip('\0')

    def listAll(self):
        users = Users.query.filter().all()
        return users

    def create(self):
        payload = request.get_json()
        if payload == None:
            return {
                'desc': 'No payload is provided to create employee.',
                'code': 400
            }

        # Check for duplication
        userSave = Users(payload)
        userSave.save()

        return {
            'desc': '成功',
            'code': 201
        }

    def update(self, empId):
        payload = request.get_json()
        if payload == None:
            return {
                'desc': 'No payload is provided to update employee.',
                'code': 400
            }
        try:
            empIds = Users.query.filter(User.USER_ID==empId).first()
            
            empIds.USERNAME=payload['USERNAME']
            empIds.CREATED_BY=payload['CREATED_BY']
            empIds.CREATED_DATE=payload['CREATED_DATE']
            db.session.commit()
            
            return {'desc': "成功", 'code': 200}
        except:
            return {
                'desc': 'ID为 %s 的数据不存在.' % empId,
                'code': 400
            }

    def delete(self, empId):
        try:
            empIds = Users.query.filter(User.USER_ID==empId).first()
            db.session.delete(empIds)
            db.session.commit()  
            return {'desc': "成功", 'code': 200}
        except:
            return {
                'desc': 'ID为 %s 的数据不存在.' % empId,
                'code': 400
                }
    
    def login(self):
        payload = request.get_json()
        
        if payload == None:
            return {
                'desc': 'No payload is provided to create employee.',
                'code': 400
            }

        code = payload['code']
        iv = payload['iv']      
        encryptedData = payload['encryptedData']
        url = 'https://api.weixin.qq.com/sns/jscode2session?appid={{appid}}&secret={{secret}}&js_code=%s&grant_type=authorization_code' % (str(code))
        headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36'
        }
        res = requests.get(url, headers=headers)
        openid = res.json()['openid']
        session_key = res.json()['session_key']
        encrypted_skey = User.encrypt(session_key) # 加密
        encrypted_openid = User.encrypt(openid)  # 加密
        encrypted_skeystr = str(encrypted_skey, encoding = "utf8")
        token =  str(encrypted_openid, encoding = "utf8") 
        if Users.query.filter(Users.openid == openid).first():
            return {
                'desc': 'ID为  的数据不存在.',
                'code': 200
                }
        else :
            User.register(code,session_key,encryptedData,iv)
            return {
                'desc': 'ID为  的数据不存在.',
                'code': 200
                }

    
    def register(code,session_key,encryptedData,iv):
        appId = '{{appid}}'
        pc = WXBizDataCrypt(appId, session_key)
        
        user = pc.decrypts(encryptedData, iv)
        us = Users(user['openId'],user['nickName'],user['gender'],user['language'],user['city'],user['province'],user['country'],user['avatarUrl'])
        us.save()
        